#pragma once
#include<iostream>
#include<functional>
#include"Socket.hpp"
#include"InetAddr.hpp"
#include"Protocol.hpp"


using namespace socket_ns;
using process_t = std::function<std::shared_ptr<Response>(std::shared_ptr<Request>)>;

class IOService
{
public:
    IOService(process_t process):_process(process)
    {}
    void Excute(SockSPtr sock,InetAddr &addr)
    {
        std::string packstreamqueue;
        while(true)
        {   
            ssize_t n=sock->Recv(&packstreamqueue);
            if(n<=0)
            {
                LOG(INFO,"client %s  quit or recv error\n",addr.Ip().c_str());
                break;
            }
            std::cout<<"packstreamqueue:\n"<<packstreamqueue<<std::endl;
            std::string json=Decode(packstreamqueue);
            if(json.empty())continue;

            auto req=Factory::BuildRequestDefault();
            req->DeSerialize(json);
            auto resp=_process(req);   
            std::cout<<"json:\n"<<json<<std::endl; 

            std::string respjson;
            resp->Serialize(&respjson);
            respjson=Encode(respjson);
            std::cout<<"respjson:\n"<<respjson<<std::endl;
            sock->Send(respjson);
            
        }   
    }
    ~IOService()
    {}
private:
    process_t _process;

};